// ============================== 导入依赖 ============================== //

import CORE from '@login/CORE'
import TRANS from '@demo/CORE/UTIL/init/TRANS'

import Client from '@api/base/api/SysPropertyApi'

import ComClass from '@api/ComQuery'
import TreeClass from '@api/base/model/QuerySysPropertyListReq'
import BaseClass from '@api/base/model/SysPropertyDto'

const CLIENT = CORE.grpcCLIENT(Client)
const PARAM = { page: 1, pageSize: 10000 }
const COM = [ComClass, 'comQuery']
const BASE = [BaseClass, 'content']

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 结构树 —————————————————————————————— //

  async getProperty(name = '属性') {
    if (sessionStorage.PROPERTY) return JSON.parse(sessionStorage.PROPERTY)

    const DTO = CORE.grpcDTO(TreeClass, PARAM, COM, BASE)
    const resp = await CORE.grpc(TRANS.transTip(name), CLIENT, 'querySysPropertyList', DTO)
    const PROPERTY = transTree(resp.content || [])

    sessionStorage.PROPERTY = JSON.stringify(PROPERTY)

    return PROPERTY
  },
}

// ============================== 转换方法 ============================== //

const transTree = (arr, parentId = '') => {
  const tree = arr.filter((item) => item.parentId === parentId)
  const other = arr.filter((item) => item.parentId !== parentId)

  tree.forEach((item) => {
    const child = transTree(other, item.id)
    if (child.length) item.child = child
  })

  return tree.sort((a, b) => b.sortValue - a.sortValue)
}
